package js

import (
	"gitee.com/injoyai/goutil/conv"
	"gitee.com/injoyai/goutil/script"
)

func NewPool(num ...int) *Pool {
	length := 20
	if len(num) > 0 && num[0] > 0 {
		length = 1
	}
	p := &Pool{
		c: make(chan *Client, length),
	}
	for i := 0; i < length; i++ {
		c := New()
		p.list = append(p.list, c)
		p.put(c)
	}
	return p
}

type Pool struct {
	list []*Client
	c    chan *Client
}

func (this *Pool) get() *Client {
	return <-this.c
}

func (this *Pool) put(c *Client) {
	this.c <- c
}

func (this *Pool) Exec(text string) (val interface{}, err error) {
	c := this.get()
	defer this.put(c)
	return c.Exec(text)
}

func (this *Pool) Set(key string, value interface{}) error {
	for _, v := range this.list {
		v.Set(key, value)
	}
	return nil
}

func (this *Pool) SetFunc(key string, fn script.Func) error {
	for _, v := range this.list {
		v.SetFunc(key, fn)
	}
	return nil
}

func (this *Pool) Close() error {
	for _, v := range this.list {
		v.Close()
	}
	return nil
}

func (this *Pool) GetVar(key string) *conv.Var {
	for _, v := range this.list {
		return v.GetVar(key)
	}
	return conv.Nil()
}
